import { defineStore } from 'pinia'
import axios from '@/api'
import { storage } from "@/util"
import { ref } from 'vue'

export default defineStore('login', () => {
    let token = ref(''), userInfo = ref<any>({});
    let latitude = ref(22.9863), longitude = ref(114.7185);
    let phoneLogin = (ele: any, phoneDetail: any) => {
        return new Promise((resolve, reject) => {
            uni.login({
                provider: 'univerify',
                univerifyStyle: {
                    fullScreen: true
                },
                async success(ev) {
                    axios.get('/applet/login', { js_code: ev.code, code: phoneDetail.detail.code }, true).then(async (res: any) => {
                        token.value = res.access_token
                        uni.redirectTo({
                            url: '/pages/index/index'
                        });
                        resolve(res)
                    }).finally(() => {
                        ele?.hideLoading()
                    })
                },
                fail() {
                    reject()
                }
            })
        })
    }
    let updateUserInfo = async (detail: any) => {
        let data = {
            ...detail,
            latitude: '22.9863', longitude: '114.7185',
        }
        await axios.file('/user/update', { ...data, avatar_file: detail.avatarUrl, wechat_qrcode: detail.wechat_qrcode }, { fileNames: ['avatar_file', 'wechat_qrcode'], toast: true })
        userInfo.value = detail
        return userInfo
    }
    // 兼容旧数据格式
    setTimeout(() => {
        userInfo.value.nickname = userInfo.value.nickname || userInfo.value.nickName || ''
        userInfo.value.avatar_file = userInfo.value.avatar_file || userInfo.value.avatarUrl || ''
    })
    return { phoneLogin, token, latitude, longitude, userInfo, updateUserInfo }
}, {
    persist: {
        storage,
        paths: ['token', 'userInfo', 'latitude', 'longitude'],
    }
})

